﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HCFramework.API.LINQ;

namespace HCFramework.Product.Payment
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Title = M.Common.GetLang(this.Title);
            if (!IsPostBack)
            {
                btnContinue.Text = M.Common.GetLang(btnContinue.Text);
            }
        }

        protected void btnContinue_Click(object sender, EventArgs e)
        {
            // Order
            Order order = new Order();
            order.DeliveryType = DeliveryMethod1.SeletedMethod;
            order.PaymentMethod = PaymentMethod1.SelectedMethod;
            order.Status = (int)E.OrderStatus.Waiting;
            C.OrderController.Insert(order);

            // Order_Products
            foreach (C.CartItem cartItem in C.ShoppingCart.ListCartItem)
            {
                Order_Product op = new Order_Product();
                op.CurrencyCode = cartItem.CurrencyCode;
                op.OrderID = order.OrderID;
                op.Price = cartItem.Price;
                op.ProductID = cartItem.ProductId;
                op.Quantity = cartItem.Count;
                C.Order_ProductController.Insert(op);
            }

            // OrderContact
            OrderContact oc = ContactInfo1.Insert(order.OrderID);

            // Send email to customer
            string subject = M.FileM.Read(@"\Product\Payment\Template\EmailSubject.htm");
            string body = M.FileM.Read(@"\Product\Payment\Template\EmailBody.htm");
            subject = M.Template.MergeCurrentDomain(subject);
            body = M.Template.MergeOrder(body, order);
            body = M.Template.MergeOrderContact(body, oc);
            M.Common.SendEmail(oc.Email, subject, body);

            // Send email to admin
            subject = M.FileM.Read(@"\Product\Payment\Template\AdminEmailSubject.htm");
            body = M.FileM.Read(@"\Product\Payment\Template\AdminEmailBody.htm");
            subject = M.Template.MergeCurrentDomain(subject);
            subject = M.Template.MergeOrder(subject, order);
            body = M.Template.MergeOrder(body, order);
            M.Common.SendEmail(C.ConfigController.GetValue(E.Config.AdminEmailAddress), subject, body);

            // Clear shopping cart
            C.ShoppingCart.Clear();

            // Redirect
            Response.Redirect("~/Product/Confirmation/Default.aspx?orderIdentity=" + order.Identity);
        }
    }
}